package com.motherchild.admin.service.impl;

import com.motherchild.admin.dto.CategoryDTO;
import com.motherchild.admin.mapper.CategoryMapper;
import com.motherchild.admin.service.CategoryService;
import com.motherchild.admin.vo.CategoryVO;
import com.motherchild.common.exception.BusinessException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Override
    public List<CategoryVO> getList() {
        return categoryMapper.selectList();
    }

    @Override
    public CategoryVO getDetail(Long id) {
        CategoryVO category = categoryMapper.selectDetail(id);
        if (category == null) {
            throw new BusinessException("分类不存在");
        }
        return category;
    }

    @Override
    @Transactional
    public void add(CategoryDTO categoryDTO) {
        if (categoryDTO.getSort() == null){
            categoryDTO.setSort(1);
        }
        if (categoryDTO.getStatus() == null){
            categoryDTO.setStatus(1);
        }
            categoryMapper.insert(categoryDTO);
    }

    @Override
    @Transactional
    public void update(Long id, CategoryDTO categoryDTO) {
        CategoryVO category = categoryMapper.selectDetail(id);
        if (category == null) {
            throw new BusinessException("分类不存在");
        }
        categoryDTO.setId(id);
        categoryMapper.update(categoryDTO);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        CategoryVO category = categoryMapper.selectDetail(id);
        if (category == null) {
            throw new BusinessException("分类不存在");
        }
        // 检查是否有子分类
        List<CategoryVO> children = categoryMapper.selectByParentId(id);
        if (!children.isEmpty()) {
            throw new BusinessException("请先删除子分类");
        }
        // 检查分类下是否有商品
        int count = categoryMapper.selectProductCount(id);
        if (count > 0) {
            throw new BusinessException("分类下有商品，无法删除");
        }
        categoryMapper.delete(id);
    }

    @Override
    @Transactional
    public void updateStatus(Long id, Integer status) {
        CategoryVO category = categoryMapper.selectDetail(id);
        if (category == null) {
            throw new BusinessException("分类不存在");
        }
        categoryMapper.updateStatus(id, status);
    }
} 